package com.reactnativestudy.utils;

import android.app.Activity;
import android.content.Context;
import android.content.MutableContextWrapper;
import android.util.Log;

import com.facebook.react.PackageList;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactInstanceManagerBuilder;
import com.facebook.react.ReactRootView;
import com.facebook.react.bridge.CatalystInstance;
import com.facebook.react.common.LifecycleState;
import com.reactnativestudy.model.ReactBundle;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ReactViewCache {
    Map<String, ReactRootView> rootViewMap = new HashMap<>();
    private static final String TAG = "ReactViewCache";
    private static ReactViewCache instance = null;

    public static ReactViewCache getInstance() {
        if (instance == null) {
            instance = new ReactViewCache();
        }
        return instance;
    }

    private void loadBundleFile(Context context, CatalystInstance instance, ReactBundle reactBundle) {
        if (instance == null) {
            return;
        }
        String cachePath = Utils.getCachePath(context);
        List<ReactBundle> dependencies = reactBundle.getDependencies();
        if (dependencies != null && dependencies.size() > 0) {
            for (ReactBundle bundle :
                    dependencies) {
                loadBundleFile(context, instance, bundle);
            }
        }
        String dir = cachePath + "/" + reactBundle.getHash() + "/";
        instance.loadScriptFromFile(dir + reactBundle.getEntry(), dir, false);

    }

    public void init(Activity activity, String name, ReactBundle reactBundle) {
        Context ctx = new MutableContextWrapper(activity);
        ReactRootView rootView = new ReactRootView(ctx);

        ReactInstanceManagerBuilder builder = ReactInstanceManager.builder()
                .setApplication(activity.getApplication())
                .setJSMainModulePath("index")
                .setJSBundleFile("assets://empty")
                .addPackages(new PackageList(activity.getApplication()).getPackages())
                .setUseDeveloperSupport(false)
                .setInitialLifecycleState(LifecycleState.BEFORE_CREATE);
        ReactInstanceManager manager = builder.build();
        manager.addReactInstanceEventListener(context -> {
            Log.v(TAG, reactBundle.toString());
            CatalystInstance instance = context.getCatalystInstance();
            Log.v(TAG, "loadScript: " + System.currentTimeMillis());
            loadBundleFile(activity.getApplicationContext(), instance, reactBundle);
            Log.v(TAG, "loadScripted: " + System.currentTimeMillis());
            rootView.startReactApplication(manager, "ReactNativeStudy");
            Log.v(TAG, "startReactApplication: " + System.currentTimeMillis());
        });
        manager.createReactContextInBackground();
        setDelegate(name, rootView);
    }

    public void setDelegate(String key, ReactRootView rootView) {
        rootViewMap.put(key, rootView);
    }

    public ReactRootView getDelegate(Activity activity, String key) {
        ReactRootView rootView = rootViewMap.get(key);
        if (rootView != null) {
            ((MutableContextWrapper) rootView.getContext()).setBaseContext(activity);
        }
        return rootView;
    }
}

